<template>
  <div style="width: 1000px; margin: 50px auto">
    <el-form :model="good">
      <el-form-item label="商品名称" label-width="150px">
        <el-input
          v-model="good.name"
          autocomplete="off"
          style="width: 80%"
        ></el-input>
      </el-form-item>
      <el-form-item label="商品描述" label-width="150px">
        <el-input
          v-model="good.description"
          autocomplete="off"
          style="width: 80%"
        ></el-input>
      </el-form-item>
      <el-form-item label="规格" label-width="150px">
        <el-tag
          closable
          @close="handleClose(standard)"
          :disable-transitions="true"
          style="margin-right: 10px"
          v-for="(standard, index) in standards"
          :key="index"
          @click="editStandard(index)"
        >
          {{ standard.value }}
        </el-tag>
        <el-button icon="el-icon-plus" circle @click="addStandard"></el-button>
      </el-form-item>

      <el-form-item label="折扣" label-width="150px">
        <el-input
          v-model="good.discount"
          autocomplete="off"
          style="width: 80%"
        ></el-input>
      </el-form-item>

      <el-form-item label="分类" label-width="150px">
        <el-select v-model="good.categoryId" placeholder="请选择">
          <el-option
            v-for="item in categoryItems"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品图片" label-width="150px">
        <el-upload
          class="upload-demo"
          ref="upload"
          :action="baseApi + '/file/upload'"
          :file-list="fileList"
          :on-change="handleChange"
          :limit="1"
          :on-remove="handleRemove"
          :on-success="handleImgSuccess"
          :auto-upload="false"
        >
          <el-button slot="trigger" size="small" type="primary"
            >选取文件</el-button
          >
          <div slot="tip" class="el-upload__tip">
            只能上传一个jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label-width="150px">
        <el-button type="success" @click="submit" style="font-size: 20px"
          >提交</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogFormVisible"
      title="规格信息"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="standard">
        <el-form-item label="规格名称" label-width="150px">
          <el-input
            v-model="standard.value"
            autocomplete="off"
            style="width: 80%"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格" label-width="150px">
          <el-input
            v-model="standard.price"
            autocomplete="off"
            style="width: 80%"
          ></el-input>
        </el-form-item>
        <el-form-item label="库存" label-width="150px">
          <el-input
            v-model="standard.store"
            autocomplete="off"
            style="width: 80%"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogFormVisible = false" style="font-size: 20px"
          >取消</el-button
        >
        <el-button type="primary" @click="saveStandard" style="font-size: 20px"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";

const store = useStore();
const route = useRoute();
const router = useRouter();

// Reactive data
const baseApi = ref<string>(store.state.baseApi);
const good = ref<any>({ discount: "1" });
const standards = ref<any[]>([]);
const standard = ref<any>({});
const fileList = ref<any[]>([]);
const dialogFormVisible = ref<boolean>(false);
const categoryItems = ref<any[]>([]);
const upload = ref<any>(null);

// Lifecycle
onMounted(() => {
  store.state.request.get("/api/category").then((res: any) => {
    if (res.code === "200") {
      categoryItems.value = res.data;
    }
    if (route.query.good) {
      good.value = JSON.parse(route.query.good as string);
      fileList.value = [{ name: "原始图片", url: good.value.imgs }];

      store.state.request
        .get("/api/good/standard/" + good.value.id)
        .then((res: any) => {
          if (res.code === "200") {
            standards.value = JSON.parse(res.data);
          }
        });
    }
  });
});

// Methods
const editStandard = (index: number) => {
  standard.value = standards.value[index];
  dialogFormVisible.value = true;
};

const addStandard = () => {
  standard.value = {};
  dialogFormVisible.value = true;
};

const saveStandard = () => {
  if (!standard.value.value?.trim()) {
    store.state.message.error("请输入规格名称");
    return;
  }
  if (!standard.value.price) {
    store.state.message.error("请输入价格");
    return;
  }
  if (!standard.value.store) {
    store.state.message.error("请输入库存");
    return;
  }

  standards.value.push(standard.value);
  dialogFormVisible.value = false;
};

const handleClose = (standard: any) => {
  standards.value = standards.value.filter((item) => item !== standard);
};

const handleImgSuccess = (res: any) => {
  good.value.imgs = res.data;
  save();
};

const handleChange = (file: any, files: any[]) => {
  fileList.value = files.slice(-1);
};

const handleRemove = () => {
  fileList.value.pop();
};

const submit = () => {
  if (!good.value.name?.trim()) {
    store.state.message.error("请输入商品名称");
    return;
  }
  if (!good.value.description?.trim()) {
    store.state.message.error("请输入商品描述");
    return;
  }
  if (standards.value.length === 0) {
    store.state.message.error("请至少添加一个规格");
    return;
  }
  if (!good.value.discount) {
    store.state.message.error("请输入商品折扣");
    return;
  }
  if (!good.value.categoryId) {
    store.state.message.error("请选择商品分类");
    return;
  }
  if (fileList.value.length === 0) {
    store.state.message.error("请上传图片");
    return;
  }

  if (fileList.value[0].status === "ready") {
    upload.value.submit();
  } else if (fileList.value[0].status === "success") {
    save();
  }
};

const save = () => {
  store.state.request.post("/api/good", good.value).then((res: any) => {
    if (res.code === "200") {
      good.value.id = res.data;
      store.state.request
        .post(`/api/good/standard?goodId=${good.value.id}`, standards.value)
        .then((res: any) => {
          if (res.code === "200") {
            store.state.message.success("操作成功");
            router.go(-1);
          } else {
            store.state.message.error("操作失败");
          }
        });
    } else {
      store.state.message.error(res.msg);
    }
  });
};
</script>

<style scoped></style>
